package com.dddframework.security.domain.auth.model;

import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;

import java.util.Collection;

/**
 * 用户
 */
@Setter
@Getter
public class AuthUser extends User {
    /**
     * 用户ID
     */
    private String id;
    /**
     * -1、系统管理员；1、租户管理员；2、店铺管理员, 6、司机 9、师傅
     */
    private String type;
    /**
     * 租户ID
     */
    private String tenantId;

    public AuthUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
        super(username, password, authorities);
    }

    /**
     * 获取当前用户的全部信息 EnableBaseResourceServer true
     * 获取当前用户的用户名 EnableBaseResourceServer false
     *
     * @return BaseUser
     */
    public static AuthUser of(Authentication authentication) {
        if (authentication == null) {
            return null;
        }
        Object principal = authentication.getPrincipal();
        if (principal instanceof AuthUser) {
            return (AuthUser) principal;
        }
        return null;
    }

    /**
     * 获取用户
     */
    public static AuthUser of() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return of(authentication);
    }
}